var resourceDetail;
var book;
var resourceId;
var userFrom;

//视频状态：0 首次播放，1 播放中，2 暂停，3 结束
var videoStatus = 0;

//视频观看时长记录
var videoDuration = 0;

//视频开始时间
var startTime = 0;

//临时播放时间
var tempDuration = 0;

//定时方法（结束时使用）
var timerMethod;

var my_timer;

var globalId;

var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;

var player;

var initPlayer = function (source) {
    player = new Aliplayer({
            "id": "my_video",
            "source": source,
            "width": "100%",
            "autoplay": false,
            "x5_type": "h5",
            "isLive": false,
            "rePlay": false,
            "playsinline": true,
            "preload": true,
            "controlBarVisibility": "always",
            "useH5Prism": true,
            "skinLayout": [
                {
                    "name": "bigPlayButton",
                    "align": "blabs",
                    "x": 30,
                    "y": 80
                },
                {
                    "name": "H5Loading",
                    "align": "cc"
                },
                {
                    "name": "errorDisplay",
                    "align": "tlabs",
                    "x": 0,
                    "y": 0
                },
                {
                    "name": "infoDisplay"
                },
                {
                    "name": "tooltip",
                    "align": "blabs",
                    "x": 0,
                    "y": 56
                },
                {
                    "name": "thumbnail"
                },
                {
                    "name": "controlBar",
                    "align": "blabs",
                    "x": 0,
                    "y": 0,
                    "children": [
                        {
                            "name": "progress",
                            "align": "blabs",
                            "x": 0,
                            "y": 44
                        },
                        {
                            "name": "playButton",
                            "align": "tl",
                            "x": 15,
                            "y": 12
                        },
                        {
                            "name": "timeDisplay",
                            "align": "tl",
                            "x": 10,
                            "y": 7
                        },
                        {
                            "name": "fullScreenButton",
                            "align": "tr",
                            "x": 10,
                            "y": 12
                        }
                    ]
                }
            ]
        }, function (player) {
            console.log("The player is created");
        }
    );

    player.on('play',playF);
    player.on('pause',pauseF);
    player.on('ended',endedF);

    player.on("x5requestFullScreen",function(e){
        $("#info").addClass("sc");
    })
    player.on('x5cancelFullScreen',function(e){
        $("#info").removeClass("sc");
    })

}

var getUserInfo = function () {
    $.ajax({
        type: "POST",
        url: "../api/home/getUserInfo",
        contentType: "application/x-www-form-urlencoded",
        success: function (r) {
            if (r.code === 0) {
                console.log("获取用户身份");
                console.log(r);
                if (!r.identity) {
                    showSelectIdent();
                }
            } else {
                $.toast(r.msg, "text");
            }
        }
    });
}

var showSelectIdent = function () {
    $.modal({
        title: "身份",
        text: "请选择您的身份，我们之后会根据您选择的身份给你推送对应的内容，请慎重选择",
        buttons: [
            {
                text: "学生", onClick: function () {
                    setIdent(0)
                }
            },
            {
                text: "家长", onClick: function () {
                    setIdent(1)
                }
            },
            {
                text: "老师", onClick: function () {
                    setIdent(2)
                }
            },
        ]
    });
}
var setIdent = function (ident) {
    $.ajax({
        type: "POST",
        url: "../api/default/saveUserIdentity",
        data: {
            identity: ident
        },
        contentType: "application/x-www-form-urlencoded",
        success: function (r) {
            if (r.code === 0) {
                $.toast("设置身份成功", "text");
            } else {
                $.toast(r.msg, "text");
            }
        }
    });
}

//获取视频详情
var getVideoDetail = function () {
    $.ajax({
        type: "GET",
        url: "../api/resource/" + resourceId,
        contentType: "application/json",
        success: function (r) {
            if (r.code === 0) {
                console.log("获取资源详情")
                console.log(r)
                resourceDetail = r.resourceDetail;
                book = r.resourceDetail.book;
                fillDeatilData();
            } else {
                $.toast(r.msg, "text");
            }
        }
    });
}

var fillDeatilData = function () {
    var baseInfo = book.grade.name + ">" + book.subject.name + ">" + book.version.name + ">" + book.season.name;
    $("#base-info").html(baseInfo);
    $("#video-info").html(resourceDetail.videoName);

    if (resourceDetail.videoUrl) {
        $("#my_video").css("display", "block");
        initPlayer(resourceDetail.videoUrl);
/*        $("#my_video").attr("src", resourceDetail.videoUrl);
        $("#my_video").attr("poster", resourceDetail.videoUrl + "?x-oss-process=video/snapshot,t_1000,m_fast");*/

    }
    if (resourceDetail.resourceUrl) {
        if (resourceDetail.videoUrl) {
            $("#download-resources-button").css("display", "inline");
            $("#download-resources-button").attr("href", resourceDetail.resourceUrl);
        } else {
            $(".cover-img").css("display", "block");
            if(isAndroid){
                $("#android-download-resources-home").css("display", "inline");
            }
            $(document).on("click", "#download-resources-home", function () {
                if(isAndroid){
                    window.open('../public/plugins/pdfjs/web/viewer.html?file=' + resourceDetail.resourceUrl,'PDF','width:50%;height:50%;top:100;left:100;');
                } else {
                    window.location.href = resourceDetail.resourceUrl;
                }
            });

            $(document).on("click", "#android-download-resources-home", function () {
                window.location.href = resourceDetail.resourceUrl;
            });

        }
    }

}

$(document).on("click", "#test-button", function () {
    setClick(1);
});
$(document).on("click", "#return-list", function () {
    window.location.href = './resource-list.html?bookId=' + book.id
});

my_timer = function () {

    tempDuration = Date.parse(new Date());

    if (tempDuration - startTime > 15000) {
        videoDuration += tempDuration - startTime;
        startTime = Date.parse(new Date());
        userVideoRecord(videoDuration, "1");
    }
}

var playF = function () {
    startTime = Date.parse(new Date());
    timerMethod = window.setInterval("my_timer()", 500);
    console.log("执行了，定时后的代码");
    if (videoStatus == 0) {

        setViews();
        userVideoRecord(videoDuration, "0");
    }
    videoStatus = 1;
}


var pauseF = function () {

    videoDuration += tempDuration - startTime;
    window.clearInterval(timerMethod);

    if (tempDuration - startTime > 5000) {
        userVideoRecord(videoDuration, "2");
    }
    videoStatus = 2;
}


var endedF = function () {
    console.log("播放结束100006");
    videoStatus = 3;
    videoDuration += tempDuration - startTime;
    window.clearInterval(timerMethod);
    startTime = Date.parse(new Date());
    tempDuration = Date.parse(new Date());
    userVideoRecord(videoDuration, "3");
}


function guid() {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(24).substring(1);
    }

    return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
}

var initPutVideoInfo = function () {
    sendTest(0);
    globalId = guid();
    pushHistory();
    window.addEventListener("popstate", function (e) {
        console.log("进入退出页面方法");

        if (videoStatus == 1) {

            videoDuration += tempDuration - startTime;
            userVideoRecord(videoDuration, "4");
        }
        window.history.go(-1);
    }, false);

    function pushHistory() {
        var state = {
            title: "title",
            url: "#"
        };
        window.history.pushState(state, "title", "#");
    }
}

var userVideoRecord = function (duration, status) {
    console.log(duration);
    duration = duration == 0 ? 0 : duration / 1000;
    var totalTime = $("#my_video")[0].duration;
    if (isNaN(totalTime)) {
        totalTime = 0;
    }

    $.ajax({
        type: "POST",
        url: "../api/video/userVideoRecord",
        data: {
            globalId: globalId,
            duration: duration,
            userFrom: userFrom,
            videoStatus: status,
            videoId: resourceDetail.id,
            totalTime: totalTime,
            currentTime: parseInt($("#my_video")[0].currentTime)
        },
        contentType: "application/x-www-form-urlencoded",
        success: function (r) {
            if (r.code === 0) {
                console.log("上报成功")
                console.log(r)
            } else {
                $.toast(r.msg, "text");
            }
        }
    });
}

//获取统计信息
var getCountInfo = function () {
    $.ajax({
        type: "POST",
        url: "../api/default/getCount",
        data: {
            videoId: resourceId
        },
        contentType: "application/x-www-form-urlencoded",
        success: function (r) {
            if (r.code === 0) {
                console.log("获取统计信息成功")
                console.log(r)
                console.log(r.count)
                if(r.count){
                    if(r.count.zan){
                        $("#click-count").text(r.count.zan);
                    }else{
                        $("#click-count").text(0);
                    }
                    if(r.count.viewNumber){
                        $("#view-count").text(r.count.viewNumber);
                    }else{
                        $("#view-count").text(0);
                    }
                }else{
                    $("#view-count").text(0);
                    $("#click-count").text(0);
                }

                if(r.isClick){
                    $('#zan-style').addClass('icon-38');
                }else {
                    $('#zan-style').addClass('icon-65');
                }
            }
        }
    });
}

//设置点赞信息
var setZan = function (status) {
    $.ajax({
        type: "POST",
        url: "../api/default/setZan",
        data: {
            videoId: resourceId,
            status: status
        },
        contentType: "application/x-www-form-urlencoded",
        success: function (r) {
            if (r.code === 0) {
                console.log("设置点赞成功")
                console.log(r)
            }
        }
    });
}

//设置视频总观看数
var setViews = function () {
    $.ajax({
        type: "POST",
        url: "../api/default/setViews",
        data: {
            videoId: resourceId
        },
        contentType: "application/x-www-form-urlencoded",
        success: function (r) {
            if (r.code === 0) {
                console.log("设置视频观看成功")
                console.log(r)
                var val = $("#view-count").text();
                $("#view-count").text(parseInt(val) + 1);
            }
        }
    });
}

//绑定点击事件
$(document).on("click", ".click-method", function () {
    if ($('#zan-style').hasClass('icon-38')) {
        $('#zan-style').removeClass('icon-38').addClass('icon-65');
        var val = $("#click-count").text();
        if(parseInt(val) > 0){
            $("#click-count").text(parseInt(val) - 1);
            setZan(0);
        }
    } else {
        $('#zan-style').addClass('icon-38').removeClass('icon-65');
        var val = $("#click-count").text();
        $("#click-count").text(parseInt(val) + 1);
        setZan(1);
    }
});

$(document).on("click", "#dongle", function () {
    sendTest(1);
});
$(document).on("click", "#budong", function () {
    sendTest(2);
});
//发送测试方法
var sendTest = function (status) {
    $.ajax({
        type: "POST",
        url: "../api/home/setUserVideoInfo",
        data: {
            videoId: resourceId,
            status:status
        },
        contentType: "application/x-www-form-urlencoded",
        success: function (r) {
            if (r.code === 0) {
                console.log("设置成功")
                console.log(r)
                if(status === 1){
                    alert("你的进步神速，真棒！");
                }else if(status ===2){
                    alert("建议再仔细看一遍，加油！");
                }
            }
        }
    });
}
